<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <el-card>
        <el-form
          :rules="rules"
          :inline="true"
          ref="conncectFormRef"
          :model="connectForm"
          class="form-contain"
          size="small"
        >
          <el-form-item
            :label="t('general.ip')"
            prop="ip"
          >
            <el-input
              v-model="connectForm.ip"
              :disabled="generalClientStatus"
              :placeholder="t('general.ip')"
              @keuyp.enter="connect(conncectFormRef)"
            />
          </el-form-item>
          <el-form-item
            :label="t('general.port')"
            prop="port"
          >
            <el-input
              type="number"
              v-model.number="connectForm.port"
              :disabled="generalClientStatus"
              :placeholder="t('general.port')"
              @keuyp.enter="connect(conncectFormRef)"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              :type="generalClientStatus ? 'danger' : 'primary'"
              @click="connect(conncectFormRef)"
              :loading="loading"
            >
              {{
                t(
                  generalClientStatus ? 'general.disconnect' : 'general.connect'
                )
              }}
            </el-button>
          </el-form-item>
        </el-form>

        <el-form
          ref="ruleFormRef"
          :model="generalForm"
          :rules="rules"
          class="demo-ruleForm"
          label-position="top"
          size="small"
        >
          <el-form-item
            :label="t('general.message')"
            prop="message"
          >
            <el-input
              type="textarea"
              :rows="18"
              :placeholder="t('general.message')"
              v-model="generalForm.message"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
              :disabled="!generalClientStatus"
              :loading="loading"
            >
              {{ t('general.send') }}
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">
              {{ t('general.reset') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="18">
      <Log />
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import {
  ElMessage,
  FormInstance,
  FormRules,
  TabsPaneContext,
} from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import Log from '@/components/Log/generalLog.vue'
import {
  closeClient,
  creatClient,
  sendMessageByClient,
  sendMessageByServer,
} from '@/api/general'
import { useI18n } from 'vue-i18n'
import { generalStore } from '@/store/generalStore'
import { storeToRefs } from 'pinia'
import { GeneralMessage } from '@/types/general'
const { t } = useI18n()

const loading = ref(false)

const store = generalStore()
const ruleFormRef = ref<FormInstance>()

const generalForm: GeneralMessage = reactive({
  message: '',
})

// initWebSocket('simulator')
const { generalClientStatus, generalClientIp, generalClientPort } =
  storeToRefs(store) // 连接状态

// 连接信息表单
const connectForm = reactive({
  ip: generalClientIp.value,
  port: generalClientPort.value,
})

// 表单校验规则
const rules = reactive<FormRules>({
  ip: [{ required: true, message: '请填写IP地址', trigger: 'blur' }],
  port: [
    {
      required: true,
      message: '请填写连接端口',
      trigger: 'change',
    },
    { type: 'number', message: '端口号必须为数字类型' },
  ],
  message: [
    {
      required: true,
      message: '请填写报文',
      trigger: 'change',
    },
  ],
})

// 创建客户端
const conncectFormRef = ref<FormInstance>()
const connect = async (formEl: FormInstance | undefined) => {
  // 储存ip和port，解决刷新丢失
  store.setGeneralClientIp(connectForm.ip)
  store.setGeneralClientPort(connectForm.port)

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      if (generalClientStatus.value) {
        // 断开连接
        closeClient()
          .then((res) => {
            store.setGeneralClientStatus(false)
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        // 建立连接
        creatClient(connectForm.ip, connectForm.port)
          .then((res) => {
            store.setGeneralClientStatus(true)
          })
          .finally(() => {
            loading.value = false
          })
      }
    }
  })
}

// 发送消息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      sendMessageByClient(generalForm)
        .then((res) => {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'success',
            duration: 1000,
          })
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 重置消息表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>
<style scoped lang="scss">
.form-contain {
  margin-bottom: 20px;
}
</style>
